package com.phonebook.config;

import com.phonebook.interceptor.SysInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.HashMap;
import java.util.Map;

/**
 * web配置
 *
 * @author 高旭
 * @date 2021-05-24
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${imageFilePath}")
    private String imageFilePath;

    /**
     * 跨域配置
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  //配置哪些api可以被跨域访问
                .allowedOrigins("*")    //配置哪些来源的请求可以跨域访问
                .allowCredentials(true) // 允许发送Cookie
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")   // 请求方式
                .maxAge(3600);  // 有效时间
    }

    /**
     * 请求拦截配置
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] patterns = new String[]{"/login", "/**.html", "/**.css","/**.js","/image","/swagger-resources","/favicon.ico","/v2/**","/error"};
        registry.addInterceptor(new SysInterceptor())
                .addPathPatterns("/**")                 //需要拦击的请求
                .excludePathPatterns(patterns);         //不需要拦截的请求
    }

    /**
     * 静态资源配置   静态资源映射
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**")
                .addResourceLocations("file:E:\\userImages\\");     //linux的话：file:/home/userImages/
    }
}
